package com.hrt.manage.stock.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.hrt.base.BaseController;
import com.hrt.bean.BackGoods;
import com.hrt.bean.GiftDetail;
import com.hrt.bean.GiftInfor;
import com.hrt.bean.ProductDetails;
import com.hrt.bean.ProductInfor;
import com.hrt.bean.ResourceType;
import com.hrt.bean.SnCodeSequence;
import com.hrt.bean.StockDetail;
import com.hrt.bean.StockSources;
import com.hrt.bean.Stocks;
import com.hrt.bean.StocksAction;
import com.hrt.manage.product.service.GiftDetailService;
import com.hrt.manage.product.service.GiftInforService;
import com.hrt.manage.product.service.ProDetailsService;
import com.hrt.manage.product.service.ProInforService;
import com.hrt.manage.sequence.service.SequenceService;
import com.hrt.manage.sncode.service.SNCodeService;
import com.hrt.manage.stock.service.StockDetailService;
import com.hrt.manage.stock.service.StocksService;
import com.hrt.vo.StockDetailVO;
import com.hrt.vo.StocksVO;

@Controller
@RequestMapping("manage/stocks")
public class StocksController extends BaseController<Stocks> {

	@Autowired
	private StocksService stocksService;

	@Autowired
	private StockDetailService stocksDetailService;

	@Autowired
	private ProInforService proInforService;

	@Autowired
	private ProDetailsService proInforDetailService;

	@Autowired
	private GiftInforService giftInforService;

	@Autowired
	private GiftDetailService giftInforDetailService;

	@Autowired
	private SNCodeService snCodeService;
	

	@Autowired
	private SequenceService sequenceService;

	private Boolean isInit = true;

	private List<Map<String, Object>> actions;

	private List<Map<String, Object>> reTypes;

	private List<Map<String, Object>> stockSource;
	/**
	 * 库单详情列表
	 */
	private List<Map<Long, StockDetailVO>> details;

	private StocksVO stock;

	/**
	 * 查询库存列表
	 * 
	 * @param proId
	 * @param reType
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/list")
	public ModelAndView list(
			@RequestParam(value = "retype", required = false) Integer reType,
			HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView();
		isInit = true;
		view.setViewName("manage/stocks/list");

		List<Stocks> resultList = new ArrayList();
		actions = this.getActions();
		reTypes = this.getReTypes();
		stockSource = getStockSource();
		if (reType != null) {
			if (reType.equals(ResourceType.PRODUCT_RESOURCE)
					|| reType.equals(ResourceType.GIFT_RESOURCE)) {

				resultList = stocksService.getProductByReType(reType,
						this.getPageIndex(), this.getPageSize());
				setTotalCount(stocksService.totalCount(reType));
				this.setPageCount(this.computePageCount(this.getTotalCount(),
						this.getPageSize()));
				page = this.getPage();

			} else {
				// send error message...
			}
		} else {

			setTotalCount(0l);
			this.setList(resultList);
			this.setPageCount(this.computePageCount(this.getTotalCount(),
					this.getPageSize()));
			page = this.getPage();
		}

		view.addObject("pageResult", page);
		view.addObject("actions", actions);
		view.addObject("stockSource", stockSource);
		view.addObject("reTypes", reTypes);

		return view;
	}

	@RequestMapping(value = "/listStock")
	public ModelAndView listStock(
			@RequestParam(value = "retype", required = false) Integer retype,
			@RequestParam(value = "actStr", required = false) Integer actStr,
			HttpServletRequest request, HttpServletResponse response) {

		ModelAndView view = new ModelAndView();
		view.setViewName("manage/stocks/list");
		actions = this.getActions();
		reTypes = this.getReTypes();
		stockSource = getStockSource();
		if (retype.equals(ResourceType.PRODUCT_RESOURCE)
				|| retype.equals(ResourceType.GIFT_RESOURCE)) {
			List<Stocks> resultList = new ArrayList<Stocks>();
			resultList = stocksService.getProductByReType(retype,
					this.getPageIndex(), this.getPageSize());
			this.setTotalCount(stocksService.totalCount(retype));

			setTotalCount(new Long(resultList.size()));
			setList(resultList);
			setPageCount(this.computePageCount(this.getTotalCount(),
					this.getPageSize()));
			page = this.getPage();

		} else {
			// send error message...
		}
		view.addObject("pageResult", page);
		view.addObject("actions", actions);
		view.addObject("stockSource", stockSource);
		view.addObject("action", actStr);
		view.addObject("reTypes", reTypes);
		view.addObject("typeId", retype);

		return view;
	}

	
	
	
	
	/**
	 * 
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/delItemConfirmById")
	@ResponseBody
	public String delItemConfirmById(@RequestParam(value = "id", required = true) Long id,
			HttpServletRequest request, HttpServletResponse response)
	{
		String sign="fail";
		if(id!=null)
		{
			Long delId=this.snCodeService.delSNCodeById(id);
			if(delId!=null)
			{
			  sign="success";	
			}
		}
		return sign;
	}
	
	/**
	 * 
	 * @param pageIndex
	 * @param pageSize
	 * @param retype
	 * @param actStr
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/queryByPage")
	@ResponseBody
	public Map<String, Object> queryByPage(
			@RequestParam(value = "pageIndex", required = false) Integer pageIndex,
			@RequestParam(value = "pageSize", required = false) Integer pageSize,
			@RequestParam(value = "retype", required = false) Integer retype,
			@RequestParam(value = "actStr", required = false) Integer actStr,
			HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		actions = this.getActions();
		reTypes = this.getReTypes();
		stockSource = getStockSource();
		if (pageSize == null || "".equals(pageSize)) {
			pageSize = 30;
		}
		if (pageIndex == null || "".equals(pageIndex)) {
			pageIndex = 1;
		}
		setPageIndex(pageIndex);

		setPageSize(pageSize);
		List<Stocks> resultList = new ArrayList();

		if (actStr == null || actStr == -1) {
			resultList = stocksService.getProductByReType(retype, pageIndex,
					pageSize);
		} else if (retype != null && retype != -1) {
			resultList = stocksService.getStockList(retype, actStr, pageIndex,
					pageSize);

		} else {
			resultList = stocksService.getProductByAction(actStr, pageIndex,
					pageSize);
		}

		setList(resultList);
		setTotalCount(new Long(resultList.size()));
		this.setPageCount(computePageCount(getTotalCount(), getPageSize()));

		page = this.getPage();

		resultMap.put("pageResult", page);
		resultMap.put("actions", actions);
		resultMap.put("typeId", retype);
		resultMap.put("stockSource", stockSource);
		resultMap.put("reTypes", reTypes);
		return resultMap;
	}

	/**
	 * 
	 * @param action
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/add")
	@ResponseBody
	public Map<String, Object> add(
			@RequestParam(value = "action", required = false) String action,
			HttpServletRequest request, HttpServletResponse response) {
		System.out.println("action is" + action);
		stock = new StocksVO();
		if (action != null) {
			if ("enter".equalsIgnoreCase(action)) {
				stock.setAction(StocksAction.ENTER_STOCKS);
				stock.setReType(ResourceType.GIFT_RESOURCE);
			}
			if ("out".equalsIgnoreCase(action)) {
				stock.setAction(StocksAction.OUT_STOCKS);
				stock.setReType(ResourceType.GIFT_RESOURCE);
			}
			if ("back".equalsIgnoreCase(action)) {
				stock.setAction(StocksAction.BACK_PROVIDER);
				stock.setReType(ResourceType.PRODUCT_RESOURCE);
			}
		}
		stock.setCreateTime(this.stocksService.getDate());
		String stockCode=this.sequenceService.getNextSequence(Stocks.class);
		stock.setStockCode(stockCode);
		stock.setCreator(getOnlineManager(request, response).getLoginName());
		stock.setIsFromOrder(new Integer(0));
		Map<String, Object> map = BaseController.transBean2Map(stock);

		return map;

	}

	/**
	 * 
	 * @param itemCondition
	 * @return
	 */
	@RequestMapping(value = "/queryProducts")
	@ResponseBody
	public Map queryProducts(
			@RequestParam(value = "condition") String itemCondition,
			HttpServletRequest request, HttpServletResponse response) {
		String condtionStr = null;
		List<ProductInfor> proList = new ArrayList<ProductInfor>();
		Map result = new HashMap();
		try {
			condtionStr = new String(itemCondition.getBytes("iso-8859-1"),
					"utf-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (condtionStr != null && !"".equals(condtionStr)) {
			proList = proInforService.queryProducts(condtionStr);
			System.out.println("queryProducts");
		}

		result.put("result", proList);
		return result;
	}

	@RequestMapping(value = "/loadProDetail")
	@ResponseBody
	public Map loadProductDetail(@RequestParam(value = "id") Long proId,
			HttpServletRequest request, HttpServletResponse response) {
		String condtionStr = null;
		List<ProductDetails> detailList = new ArrayList<ProductDetails>();
		Map result = new HashMap();

		if (proId != null && !"".equals(proId)) {
			detailList = proInforDetailService.queryByProId(proId);
			System.out.println("**************queryProductDetail");
		}

		result.put("result", detailList);
		return result;
	}
	
	/**
	 * 
	 * @param stockId
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/queryConfirmByStockId")
	@ResponseBody
	public Map queryConfirmByStockId(@RequestParam(value = "id") Long stockId,
			HttpServletRequest request, HttpServletResponse response)
	{
		
		Map result = new HashMap();
		List<StockDetailVO> details=new ArrayList<StockDetailVO>();
		List<StockDetailVO> stockDetails=this.stocksDetailService.getDetailByStockId(stockId);
		List<SnCodeSequence> snCodes=this.snCodeService.querySnCodeByStockId(stockId);
		if(snCodes!=null && !snCodes.isEmpty())
		{
			for(SnCodeSequence snCode:snCodes)
			{
				for(StockDetailVO detail:stockDetails){
				Long detailId=snCode.getUseStkDeId();
				
				if(detail.getId().longValue()==detailId.longValue()){
					StockDetailVO vo=new StockDetailVO();
					try {
						vo=(StockDetailVO) BeanUtils.cloneBean(detail);
						vo.setSnCode(snCode.getSnCode());
						details.add(vo);
					} catch (IllegalAccessException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (InstantiationException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (InvocationTargetException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (NoSuchMethodException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				}
			}
		}
		
		result.put("confirmDetails", details);
		
		return result;
		
	}

	@RequestMapping(value = "/loadGiftDetails")
	@ResponseBody
	public Map loadGiftDetails(@RequestParam(value = "id") Long giftId,
			HttpServletRequest request, HttpServletResponse response) {
		String condtionStr = null;
		List<GiftDetail> detailList = new ArrayList<GiftDetail>();
		Map result = new HashMap();

		if (giftId != null && !"".equals(giftId)) {
			detailList = this.giftInforService.getGiftDetailByGiftId(giftId);
			System.out.println("**************queryProductDetail");
		}

		result.put("result", detailList);
		return result;
	}

	@RequestMapping(value = "/queryGifts")
	@ResponseBody
	public Map queryGifts(
			@RequestParam(value = "condition") String itemCondition,
			HttpServletRequest request, HttpServletResponse response) {
		String condtionStr = null;
		List proList = new ArrayList();
		Map result = new HashMap();
		try {
			condtionStr = new String(itemCondition.getBytes("iso-8859-1"),
					"utf-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (condtionStr != null && !"".equals(condtionStr)) {
			proList = giftInforService.queryGiftInfors(condtionStr);
		}

		result.put("result", proList);
		return result;
	}

	@RequestMapping(value = "/loadGiftDetail")
	@ResponseBody
	public Map loadGiftDetail(
			@RequestParam(value = "id", required = true) Long giftId,
			HttpServletRequest request, HttpServletResponse response) {

		Map map = new HashMap();
		if (giftId != null && !"".equals(giftId)) {

			System.out.println("showshowshowshowshow " + giftId);
			GiftDetail detail = this.giftInforDetailService.getById(giftId);
			if (detail != null) {
				StockDetailVO detailVo = new StockDetailVO();
				detailVo.setProCode(detail.getGiftCode());
				detailVo.setProName(detail.getGiftName());
				detailVo.setProId(detail.getGiftId());
				detailVo.setRuleId(detail.getId());
				detailVo.setRuleCode(detail.getGdCode());
				detailVo.setRuleName(detail.getGdName());
				detailVo.setSalePrice(detail.getSalePrice());
				detailVo.setEnterPrice(detail.getEnterPrice());

				map = transBean2Map(detailVo);
//				for (Iterator<Map.Entry> itr = map.entrySet().iterator(); itr
//						.hasNext();) {
//					Map.Entry entry = itr.next();
//					if (entry.getValue() != null) {
//						System.out.println(entry.getKey().toString() + "="
//								+ entry.getValue().toString());
//					}
//				}
			}

		}
		return map;

	}

	/**
	 * 加载选定的产品规格
	 * 
	 * @param proId
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/loadProduct")
	@ResponseBody
	public Map loadProduct(
			@RequestParam(value = "id", required = true) String proId,
			HttpServletRequest request, HttpServletResponse response) {

		Map map = new HashMap();
		if (proId != null && !"".equals(proId)) {

			System.out.println("showshowshowshowshow " + proId);
			ProductDetails product = this.proInforDetailService
					.getDetailById(new Long(proId));
			if (product != null) {
				StockDetailVO detailVo = new StockDetailVO();
				detailVo.setProCode(product.getProCode());
				detailVo.setProName(product.getProName());
				detailVo.setProId(product.getProId());
				detailVo.setRuleId(product.getId());
				detailVo.setRuleCode(product.getRuleCode());
				detailVo.setRuleName(product.getRuleName());
				detailVo.setSalePrice(product.getSalePrice());
				detailVo.setEnterPrice(product.getEnterPrice());

				map = transBean2Map(detailVo);
//				for (Iterator<Map.Entry> itr = map.entrySet().iterator(); itr
//						.hasNext();) {
//					Map.Entry entry = itr.next();
//					if (entry.getValue() != null) {
//						System.out.println(entry.getKey().toString() + "="
//								+ entry.getValue().toString());
//					}
//				}
			}

		}
		return map;

	}

	@RequestMapping(value = "/getDetailsByPage")
	@ResponseBody
	public Map getDetailsByPage(
			@RequestParam(value = "pageIndex", required = false) Integer pageIndex,
			@RequestParam(value = "pageSize", required = false) Integer pageSize) {

		Map result = new HashMap();
		List page = new ArrayList();
		if (details != null && !details.isEmpty()) {
			int start = pageIndex * pageSize - pageSize;
			int end = pageIndex * pageSize;
			for (int i = start; start < end; i++) {
				Map detail = details.get(i);
				page.add(detail);
			}

		}
		result.put("page", page);
		return result;
	}

	/**
	 * 
	 * @param vo
	 * @param result
	 * @param request
	 * @param response
	 */

	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public void save(@ModelAttribute("stockItems") @Validated StocksVO vo,
			BindingResult result, HttpServletResponse request,
			HttpServletRequest response) {

		
		System.out.println(vo.getDetails());

		vo.setIsdelete(0);
		// vo.setStockCode("STOCK_001");
		vo.setStatus(0);
		// vo.setReType(new Integer(1));
		// vo.setAction(StocksAction.ENTER_STOCKS);
		vo.setCreateTime(this.stocksService.getDate());
		vo.setCreator(getOnlineManager(response, request).getLoginName());
		vo.setEditor((getOnlineManager(response, request).getLoginName()));
		vo.setEditTime(this.stocksService.getDate());

		List<StockDetailVO> detials = new ArrayList();
		if (vo.getDetails() != null) {
			for (StockDetailVO detail : vo.getDetails()) {
				detail.setIsdelete(0);
				// 1 产品，2礼品
				detail.setReType(vo.getReType());
				detail.setCreateTime(this.stocksService.getDate());
				detail.setCreator(this.getOnlineManager(response, request)
						.getLoginName());
				detail.setEditor((this.getOnlineManager(response, request)
						.getLoginName()));
				detail.setEditTime(this.stocksService.getDate());
				detials.add(detail);

			}
			vo.setDetails(detials);
			vo.setSummery(totalSummery(vo.getDetails()));

			stocksService.saveStocks(vo);
		}
		try {
			request.sendRedirect("listStock.do?retype=" + vo.getReType()
					+ "&actStr=" + vo.getAction());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public @ResponseBody Long[] delete(
			@RequestParam(value = "ids", required = true) String ids,
			HttpServletResponse response) throws IOException {
		Long[] idArr = null;
		ModelAndView view = new ModelAndView();

		if (ids != null) {
			if (ids.indexOf(",") != -1) {
				String[] idStrs = ids.split(",");
				idArr = new Long[idStrs.length];
				for (int idx = 0; idx < idStrs.length; idx++) {
					idArr[idx] = Long.parseLong(idStrs[idx]);
				}
			} else {
				idArr = new Long[] { Long.parseLong(ids) };
			}

		}
		try {
			this.stocksService.deleteById(idArr);

			return idArr;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}

	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public void update(@ModelAttribute("stockItems") StocksVO vo,
			BindingResult result, HttpServletResponse request,
			HttpServletRequest response) {
		vo.setIsdelete(0);
		// System.out.println("hello world...fuck..");
		List<StockDetailVO> confirmDetails = this.stocksDetailService
				.getDetailByStockId(vo.getId());
		Long confirmTotal = sumConfirmDetails(confirmDetails);
		if (vo.getStatus() == 1) {
			vo.setComfirmTime(this.stocksService.getDate());
			vo.setComfirmer(getOnlineManager(response, request).getLoginName());
		}

		if (vo.getId() == null) {
			vo.setCreateTime(this.stocksService.getDate());
			vo.setCreator(getOnlineManager(response, request).getLoginName());
		}
		vo.setEditor(getOnlineManager(response, request).getLoginName());
		vo.setEditTime(this.stocksService.getDate());

		System.out.println(vo.getDetails());
		List<StockDetailVO> detials = new ArrayList<StockDetailVO>();
		List<StockDetailVO> confirmDetails1 = vo.getConfirmDetails();
		List<StockDetailVO> detailInfors = vo.getDetails();
		List<SnCodeSequence> snCodes = new ArrayList<SnCodeSequence>();
		Map<Long, List<SnCodeSequence>> confirmMap = new HashMap<Long, List<SnCodeSequence>>();

		if (detailInfors != null) {

			if (vo.getAction() == StocksAction.OUT_STOCKS
					|| vo.getAction() == StocksAction.BACK_STOCKS) {
				for (StockDetailVO detail : detailInfors) {

					confirmMap.put(detail.getRuleId(),
							new ArrayList<SnCodeSequence>());
				}
				if (confirmDetails1 != null) {
					for (StockDetailVO confirmDetail : confirmDetails1) {

						if (confirmDetail.getProId() == null
								&& confirmDetail.getId() == null) {
							continue;
						}

						if (confirmMap.containsKey(confirmDetail.getRuleId())) {

							SnCodeSequence snCode = snCodeService
									.getSnCodeByCode(confirmDetail.getSnCode(),
											vo.getReType());

							List<SnCodeSequence> seqMap = confirmMap
									.get(confirmDetail.getRuleId());
							seqMap.add(snCode);
							confirmMap.put(confirmDetail.getRuleId(), seqMap);
						}

					}
				}
				if (detailInfors != null && !detailInfors.isEmpty()) {
					for (StockDetailVO detail : detailInfors) {

						detail.setIsdelete(0);
						// 1 产品，2礼品
						detail.setReType(vo.getReType());
						if (detail.getId() == null) {
							detail.setCreateTime(this.stocksService.getDate());
							detail.setCreator(this.getOnlineManager(response,
									request).getLoginName());
						}
						detail.setEditor((this.getOnlineManager(response,
								request).getLoginName()));
						detail.setEditTime(this.stocksService.getDate());

						if (confirmDetails1 != null
								&& !confirmDetails1.isEmpty()) {
							Long ruleId = detail.getRuleId();
							List<SnCodeSequence> seqMap = confirmMap
									.get(ruleId);
							if (new Long(seqMap.size()).longValue() == detail
									.getTotal()) {
								for (SnCodeSequence snCode : seqMap) {

									snCode.setUseTime(stocksService.getDate());
									snCode.setUseStkDeId(detail.getId());
									snCode.setUseStockId(vo.getId());
									snCode.setStatus(new Integer(1));
									snCodes.add(snCode);
									detail.setSnCodes(snCodes);
									detials.add(detail);

								}

							} else {
								// 出库数量与库单详情不一致
							}
						}

					}
					if (confirmDetails1 != null && !confirmDetails1.isEmpty()) {
						if (confirmTotal.longValue() == detials.size()) {

							vo.setDetails(detials);
							vo.setSummery(totalConfirmSummery(detials));
							stocksService.updateStock(vo);
						} else {
							PrintWriter pw;
							try {
								pw = request.getWriter();
								pw.write("<script>alert('实际出货数量与库单录入不符。请检查');window.location.href='listStock.do?retype="
										+ vo.getReType()
										+ "&actStr="
										+ vo.getAction() + ";</script>");
								pw.flush();
								pw.close();
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}

						}
					} else {
						for (StockDetailVO detail : detailInfors) {
							if (detail.getId() == null) {
								detail.setCreateTime(this.stocksService
										.getDate());
								detail.setCreator(this.getOnlineManager(
										response, request).getLoginName());
							}
							detail.setEditor((this.getOnlineManager(response,
									request).getLoginName()));
							detail.setEditTime(this.stocksService.getDate());

							detials.add(detail);
						}
						vo.setDetails(detials);
						vo.setSummery(totalSummery(detials));
						stocksService.updateStock(vo);
					}
				}
			} else {
				for (StockDetailVO detail : detailInfors) {
					if (detail.getId() == null) {
						detail.setCreateTime(this.stocksService.getDate());
						detail.setCreator(this.getOnlineManager(response,
								request).getLoginName());
					}
					detail.setEditor((this.getOnlineManager(response, request)
							.getLoginName()));
					detail.setEditTime(this.stocksService.getDate());

					detials.add(detail);
				}
				vo.setDetails(detials);
				vo.setSummery(totalSummery(detials));
				stocksService.updateStock(vo);
				
			}

		}
		try {
			request.sendRedirect("listStock.do?retype="
					+ vo.getReType() + "&actStr=" + vo.getAction());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private Double totalConfirmSummery(List<StockDetailVO> detials) {
		Double detailSummery = new Double(0);
		for (StockDetailVO detail : detials) {
			if (detail != null) {
				detailSummery = detailSummery.doubleValue()
						+ detail.getSalePrice();
			}
		}
		return detailSummery;
	}

	private Long sumConfirmDetails(List<StockDetailVO> confirmDetails) {
		// TODO Auto-generated method stub
		Long totals = new Long(0);
		for (StockDetailVO detail : confirmDetails) {
			totals = totals + detail.getTotal();
		}
		return totals;
	}

	/**
	 * 
	 * @param itemId
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/delItemById")
	@ResponseBody
	public boolean delItemById(
			@RequestParam(value = "id", required = true) Long itemId,
			HttpServletRequest request, HttpServletResponse response) {

		Map<String, Object> map = new HashMap<String, Object>();
		if (itemId != null && !"".equals(itemId)) {
			// Map resultMap=new HashMap<K, V>();
			System.out.println("showshowshowshowshow " + itemId);

			if (itemId != null) {

				return stocksDetailService.delItemById(itemId);

			}

		}
		return false;

	}

	
	/**
	 * 检查扫描条形码数量是否与详情数量一致
	 * @param stockId
	 * @param confirms
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/checkOutStockConfirm")
	@ResponseBody
	public Map checkOutStockConfirm(@RequestParam(value = "id", required = true) Long stockId,
			@RequestParam(value = "confirms",required = true)String[] snCodes,
			HttpServletRequest request, HttpServletResponse response)
	{
		String sign="fail";
		System.out.println("stockId="+stockId);
		System.out.println("confirms="+snCodes);
		Long confirmTotal=new Long(snCodes.length);
		List<StockDetailVO> details=stocksDetailService.getDetailByStockId(stockId);
		List<SnCodeSequence> snCodeEntites=new ArrayList();
		Map result=new HashMap();
		StocksVO stock=this.stocksService.getStockById(stockId);
		Long detailTotal=0l;
		
		for(StockDetailVO vo:details)
		{
			Long dtotal=vo.getTotal()==null?0:vo.getTotal();
			detailTotal=detailTotal+dtotal;
		}
		
		
		
		
		
		if(snCodes!=null && snCodes.length>0){
		for(String snCode:snCodes)
		{
			if(snCode!=null && !"".equals(snCode)){
				SnCodeSequence snCodeEntry=this.snCodeService.getSnCodeByCode(snCode, stock.getReType());	
				if(snCodeEntry!=null)
				{
					snCodeEntites.add(snCodeEntry);
				}
			}
			else{
				result.put("msg", "fail");
			}
		}
		if(detailTotal.intValue()==snCodeEntites.size()){
			
			result.put("msg", "success");
		}
		}else{
			result.put("msg", "fail");
		}
		
		return result;
		
		
	}
	/**
	 * 
	 * @param proId
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/show")
	@ResponseBody
	public Map show(@RequestParam(value = "id", required = true) String proId,
			HttpServletRequest request, HttpServletResponse response) {

		Map map = new HashMap();
		if (proId != null && !"".equals(proId)) {
			// Map resultMap=new HashMap<K, V>();

			stock = this.stocksService.getStockById(new Long(proId));

			if (stock != null) {
				map = transBean2Map(stock);
			}

		}
		return map;

	}

	/**
	 * 
	 * @param itemId
	 * @param reType
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/pushDetails")
	@ResponseBody
	public List pushDetails(
			@RequestParam(value = "id", required = true) Long itemId,
			@RequestParam(value = "reType", required = true) Integer reType,
			HttpServletRequest request, HttpServletResponse response) {

		if (details == null) {
			details = new ArrayList<Map<Long, StockDetailVO>>();
		}

		if (reType.equals(ResourceType.PRODUCT_RESOURCE)) {

			ProductDetails detail = proInforDetailService.getDetailById(itemId);
			StockDetailVO stockDetail = new StockDetailVO();
			Map detailMap = new HashMap();
			stockDetail.setEnterPrice(detail.getEnterPrice());
			stockDetail.setSalePrice(detail.getSalePrice());
			stockDetail.setProCode(detail.getProCode());
			stockDetail.setProName(detail.getProName());
			stockDetail.setProId(detail.getProId());
			stockDetail.setRuleCode(detail.getRuleCode());
			stockDetail.setRuleId(detail.getId());
			stockDetail.setRuleName(detail.getRuleName());

			detailMap.put(detail.getId(), stockDetail);

			details.add(detailMap);
		}
		if (reType.equals(ResourceType.GIFT_RESOURCE)) {
			GiftDetail detail = giftInforDetailService.getById(itemId);
		}

		return details;
	}

	/**
	 * 检测产品/礼品库存
	 * 
	 * @param reType
	 * @param action
	 * @param ruleId
	 * @param total
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/checkStock")
	@ResponseBody
	public String checkStock(
			@RequestParam(value = "reType", required = true) Integer reType,
			@RequestParam(value = "action", required = true) Integer action,
			@RequestParam(value = "ruleId", required = true) Long ruleId,
			@RequestParam(value = "total", required = true) Long total,
			HttpServletRequest request, HttpServletResponse response) {

		if (reType != null) {

			if (ResourceType.GIFT_RESOURCE == reType) {

				if (StocksAction.OUT_STOCKS == action) {
					Long oldTotal = giftInforDetailService
							.getGiftTotals(ruleId);
					if (oldTotal - total < 0) {
						System.out.println("oldTotal=" + oldTotal);
						System.out.println("total=" + total);
						return "fail";
					} else {
						return "success";
					}
				}
				if (StocksAction.BACK_PROVIDER == action) {
					// Long
					// oldTotal=giftInforDetailService.getGiftTotals(ruleId);
					// if(oldTotal-total<0){
					// return "fail";
					// }else{
					// return "success";
					// }

				}
			}

			if (ResourceType.PRODUCT_RESOURCE == reType) {

				if (StocksAction.OUT_STOCKS == action) {
					Long oldTotal = this.proInforDetailService
							.getProInforDetailTotals(ruleId);
					if (oldTotal - total < 0) {
						return "fail";
					} else {
						return "success";
					}
				}
				if (StocksAction.BACK_PROVIDER == action) {

				}
			}
		}
		/**
		 * reType:retype, action:actId, ruleId:itemId, total:total
		 */

		return null;

	}

	/**
	 * 查询库单详情
	 * 
	 * @param stockId
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/queryDetailByStockId")
	@ResponseBody
	public Map queryDetailByStockId(
			@RequestParam(value = "id", required = true) Long stockId,
			HttpServletRequest request, HttpServletResponse response) {
		Map result = new HashMap();
		List<StockDetailVO> deList = this.stocksDetailService
				.getDetailByStockId(stockId);
		result.put("details", deList);
		return result;
	}

	/**
	 * 统计总数
	 * 
	 * @param list
	 * @return
	 */
	private Double totalSummery(List<StockDetailVO> list) {
		// TODO Auto-generated method stub
		Double detailSummery = new Double(0);
		for (StockDetailVO detail : list) {
			if (detail != null) {
				detailSummery = detailSummery.doubleValue()
						+ detail.getSummery().doubleValue();
			}
		}
		return detailSummery;
	}

	/**
	 * 根据条形码返回一个退货单实体
	 * 
	 * @param snCode
	 * @param request
	 * @param response
	 * @return
	 */

	public Boolean getIsInit() {
		return isInit;
	}

	public void setIsInit(Boolean isInit) {
		this.isInit = isInit;
	}

	public List<Map<String, Object>> getActions() {
		actions = new ArrayList();
		actions = StocksAction.getActions();
		return actions;
	}

	public void setActions(List<Map<String, Object>> actions) {
		this.actions = actions;
	}

	public List<Map<String, Object>> getReTypes() {
		reTypes = new ArrayList();
		reTypes = ResourceType.getReType();
		return reTypes;
	}

	public void setReTypes(List<Map<String, Object>> reTypes) {
		this.reTypes = reTypes;
	}

	public List<Map<Long, StockDetailVO>> getDetails() {
		return details;
	}

	public void setDetails(List<Map<Long, StockDetailVO>> details) {
		this.details = details;
	}

	public StocksVO getStock() {
		return stock;
	}

	public void setStock(StocksVO stock) {
		this.stock = stock;
	}

	public List<Map<String, Object>> getStockSource() {
		stockSource = new ArrayList<Map<String, Object>>();
		stockSource = StockSources.getStockSource();
		return stockSource;
	}

	public void setStockSource(List<Map<String, Object>> stockSource) {
		this.stockSource = stockSource;
	}

}
